'use strict'
// https://github.com/Yasic/JS-Canvas-API-Base/blob/master/Img-ASC.js
import img from '../img/0.jpg'

export default function () {
  const w = this,
      canvas = document.getElementById('canvas'),
      ctx = canvas.getContext('2d'),
      PR = window.devicePixelRatio

  w.WW = window.innerWidth
  w.HH = window.innerHeight

  canvas.width = w.WW * PR
  canvas.height = w.HH * PR
  ctx.scale(PR, PR)
  ctx.drawImage(img, 0, 0)

  let rgb2gray = (r, g, b) => {
    return r * 0.333 + g * 0.333 + b * 0.333;
  }

  function gray2asc(gray) {
    /*32 64 96 128 160 192 224 256*/
    gray = 255 - gray;
    if (gray < 128) {
      if (gray < 64) {
        if (gray < 32) {
          return '.'
        }
        else {
          return '|'
        }
      }
      else {
        if (gray < 96) {
          return 'i'
        }
        else {
          return 's'
        }
      }
    }
    else {
      if (gray < 192) {
        if (gray < 160) {
          return 't'
        }
        else {
          return 'm'
        }
      }
      else {
        if (gray < 224) {
          return 'a'
        }
        else {
          return '@'
        }
      }
    }
  }

  let imgData = ctx.getImageData(0, 0, img.width, img.height)
  let imgDataArray = imgData.data

  let result = ''
  let lineIndex = 0
  for (let lineHeight = 0; lineHeight < img.height; lineHeight += 12){
    let lineASC = ''
    for (let lineFlag = 0; lineFlag < img.width; lineFlag += 5){
      lineIndex = (lineHeight * img.width + lineFlag) * 4;
      let r = imgDataArray[lineIndex],
          g = imgDataArray[lineIndex + 1],
          b = imgDataArray[lineIndex + 2]
      lineASC += gray2asc(rgb2gray(r, g, b))
    }
    lineASC += '\n';
    result += lineASC;
  }

  console.log(result)
  ctx.putImageData(imgData, 0, 0)
}